from PyQt5 import QtCore, QtGui, QtWidgets
from GUI.ui.Ui_test import Ui_Form
from GUI.ui.Ui_input import Ui_Dialog as UiInput
from GUI.ui.Ui_click import Ui_Dialog as UiClick
from GUI.ui.Ui_wait import Ui_Dialog as UiWait
from GUI.ui.Ui_find import Ui_Dialog as UiFind
from GUI.function_data import funtions, image_operation
from GUI.logic.execute import Execute
# import pyautogui as pg
from pyautogui import position
from lib.template import ResultTemplate
# import time
from time import time, sleep
import os
import re


class MouseThread(QtCore.QThread):
    sig = QtCore.pyqtSignal(str)
    
    def __init__(self):
        super(MouseThread, self).__init__()

    def run(self) -> None:
        while True:
            try:
                x, y = position()
                self.sig.emit(str((x,y)))
                sleep(0.2)
            except Exception as e:
                print(e)


class Work(QtCore.QThread):
    sig = QtCore.pyqtSignal(str)

    def __init__(self,test_data, test_name):
        super().__init__()
        self.test_data = test_data
        self.test_name = test_name

    def run(self) -> None:
        exe = Execute(self.test_data, self.test_name)
        res = exe.run()
        while True:
            try:
                msg = res.__next__()
                self.sig.emit(msg)
                if msg == 'failed':
                    raise Exception('test Failed')
            except Exception as e:
                # self.textBrowser.append("test end")
                self.sig.emit("test end")
                break
        exe.result_to_html()


class MyWindow(QtWidgets.QWidget, Ui_Form):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.initUI()
        self.action = []
        self.data = []
        self.step = 0

    def initUI(self):
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.click_Button.setIcon(QtGui.QIcon('resources/click.png'))
        self.input_Button.setIcon(QtGui.QIcon('resources/input.png'))
        self.wait_Button.setIcon(QtGui.QIcon('resources/time.png'))
        self.find_Button.setIcon(QtGui.QIcon('resources/find.png'))

        self.test_name.setPlaceholderText("请输入测试名称")
        self.test_name.setStyleSheet("font: 75 10pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.mouse_position.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        # self.setWindowOpacity(0.9)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        self.click_Button.clicked.connect(self.click_action_event)
        self.input_Button.clicked.connect(self.input_action_event)
        self.wait_Button.clicked.connect(self.wait_action_event)
        self.find_Button.clicked.connect(self.find_action_event)

        self.show_Button.clicked.connect(self.show_button_event)
        self.start_Button.clicked.connect(self.start_Button_event)
        self.clear_Button.clicked.connect(self.clear_Button_event)
        self.save_Button.clicked.connect(self.save_Button_event)
        self.mouse_button.clicked.connect(self.mouse_button_event)
        self.mouse_button.click()
        self.mouse_button.setVisible(False)

        # 脚本tab
        self.list_refresh()

        self.refresh_button.clicked.connect(self.list_refresh)
        self.all_select.clicked.connect(self.all_select_event)
        self.all_no_select.clicked.connect(self.all_no_select_event)
        self.run_button.clicked.connect(self.run_event)

        self.listWidget.setMovement(QtWidgets.QListView.Movement.Free)
        self.listWidget.setDragEnabled(True)
        self.listWidget.setDragDropMode(self.listWidget.DragDropMode.InternalMove)

    def mouse_button_event(self):
        # 鼠标位置显示
        try:
            self.mouse_thread = MouseThread()
            self.mouse_thread.sig.connect(self.mouse_positon_event)
            self.mouse_thread.start()
        except Exception as e:
            print(e)

    def mouse_positon_event(self, pos):
        if pos != self.mouse_position.text():
            self.mouse_position.setText(pos)

    def show_button_event(self):
        self.data_collection()
        if len(self.data) == 0:
            self.text_browser_show("没有测试步骤")
        else:
            for d in self.data:
                self.text_browser_show(str(d))

    def run_event(self):

        chooses = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState() == QtCore.Qt.CheckState.Checked:
                chooses.append(self.listWidget.item(i).text())

        if len(chooses) > 0:
            try:
                self.setVisible(False)
                results = []
                for choose in chooses:
                    test_steps = []
                    with open(choose, 'r', encoding='utf-8-sig') as f:
                        while data := f.readline():
                            test_steps.append(eval(data))
                    exe = Execute(test_steps, choose)
                    res = exe.run()
                    msg = None
                    while True:
                        try:
                            msg = res.__next__()
                            if msg == 'failed':
                                raise Exception('test failed')
                        except Exception as e:
                            print("test end")
                            break
                    exe.result_to_html()
                    if msg == 'failed':
                        results.append((choose.split('.')[0], 'failed',f'{exe.folder}/result.html'))
                    else:
                        results.append((choose.split('.')[0], 'pass', f'{exe.folder}/result.html'))
                res = ResultTemplate(results)
                res.html_to_file(f'tmp/{int(time())}.html')
                self.setVisible(True)
            except Exception as e:
                print(e)
                self.setVisible(True)
        else:
            pass

    def all_select_event(self):
        try:
            for i in range(self.listWidget.count()):
                self.listWidget.item(i).setCheckState(QtCore.Qt.CheckState.Checked)
        except Exception as e:
            print(e)

    def all_no_select_event(self):
        try:
            for i in range(self.listWidget.count()):
                self.listWidget.item(i).setCheckState(QtCore.Qt.CheckState.Unchecked)
        except Exception as e:
            print(e)

    def list_refresh(self):
        self.listWidget.clear()
        scripts = [ f"{path}\\{file}" for path,_,file_list in os.walk('tmp') for file in file_list if re.findall(r".*\.txt", file)]
        for script in scripts:
            item = QtWidgets.QListWidgetItem(script)
            item.setCheckState(QtCore.Qt.Unchecked)
            self.listWidget.addItem(item)

    def text_browser_show(self, msg):
        self.textBrowser.append(msg)

    def is_exist_folder(self):
        if self.test_name.text():
            if not os.path.exists(f'tmp/{self.test_name.text()}'):
                os.mkdir(f'tmp/{self.test_name.text()}')
            return True
        else:
            self.text_browser_show("请输入测试名")
            return False

    def click_action_event(self):
        if self.is_exist_folder():
            self.step += 1
            self.action.append(Click(f'step{self.step}'))
            self.text_browser_show(f"{self.action[-1].obj_name}:{self.action[-1].action_name}")
            self.action[-1].show()

    def input_action_event(self):
        if self.is_exist_folder():
            self.step += 1
            self.action.append(Input(f'step{self.step}'))
            self.text_browser_show(f"{self.action[-1].obj_name}:{self.action[-1].action_name}")
            self.action[-1].show()

    def wait_action_event(self):
        if self.is_exist_folder():
            self.action.append(Wait(f'wait_step{self.step}'))
            self.text_browser_show(f"{self.action[-1].obj_name}:{self.action[-1].action_name}")
            self.action[-1].show()

    def find_action_event(self):
        if self.is_exist_folder():
            try:
                self.action.append(Find(obj_name=f'find_step{self.step}', folder_name=self.test_name.text()))
                self.text_browser_show(f"{self.action[-1].obj_name}:{self.action[-1].action_name}")
                self.action[-1].showFullScreen()
            except Exception as e:
                print(e)
        # self.action[-1].show()

    def start_Button_event(self):
        self.data_collection()
        if self.test_name.text().isspace():
            self.text_browser_show("测试名不能为空格")
        elif not self.test_name.text():
            self.text_browser_show("请输入测试名称")
        elif len(self.data) == 0:
            self.text_browser_show("没有测试步骤")
        else:
            self.hide_all_childwin()
            self.textBrowser.clear()
            try:
                self.exe = Work(self.data,self.test_name.text())
                self.exe.sig.connect(self.text_browser_show)
                self.exe.start()
            except Exception as e:
                print(e)
        # self.setVisible(False)

        # self.setVisible(True)

    def clear_Button_event(self):
        self.data = []
        self.step = 0
        self.close_all_childwin()
        self.textBrowser.clear()
        self.test_name.clear()
        return self.action.clear()

    def save_Button_event(self):
        self.data_collection()
        if self.test_name.text().isspace():
            self.text_browser_show("测试名不能为空格")
        elif not self.test_name.text():
            self.text_browser_show("请输入测试名称")
        elif len(self.data) == 0:
            self.text_browser_show("没有测试步骤")
        else:
            file_name = f'tmp/{self.test_name.text()}/{self.test_name.text()}.txt'
            if not os.path.exists(file_name):
                with open(file_name,'x',encoding='utf-8') as f:
                    for d in self.data:
                        f.write(str(d)+'\n')
                self.text_browser_show(f"保存成功,文件名为{file_name}")
            else:
                self.text_browser_show("已存在同样名称的文件，请重新命名")

    def data_collection(self):
        for win in self.action:
            if win.isVisible():
                if win.action_name == 'click':
                    self.data.append([win.action_name,
                                      win.useful_location.x(),
                                      win.useful_location.y(),
                                      win.click_number])
                elif win.action_name == 'input':
                    self.data.append([win.action_name,
                                      win.useful_location.x(),
                                      win.useful_location.y(),
                                      win.test_info])
                elif win.action_name == 'wait':
                    self.data.append([win.action_name,
                                      win.wait_time])
                elif win.action_name == 'find':
                    self.data.append([win.action_name,
                                      win.location,
                                      win.info])
        print(self.data) # [[动作，x, y, int or [int(功能序号), message]]
        self.action.clear()

    def close_all_childwin(self):
        return [win.close() for win in self.action]

    def hide_all_childwin(self):
        for win in self.action:
            if win.isVisible():
                win.setVisible(False)


class Click(QtWidgets.QDialog, UiClick):
    _startPos = None
    _endPos = None
    _isTracking = None
    useful_location = None
    action_name = 'click'
    click_number = 1
    obj_name = None

    def __init__(self, obj_name):
        super().__init__()
        self.setupUi(self)
        self.obj_name = obj_name
        self.initUI(obj_name)

    def initUI(self, obj_name):
        self.setWindowTitle(obj_name)
        self.setObjectName(obj_name)  # 设置窗口名，相当于CSS中的ID
        self.setFixedSize(QtCore.QSize(120, 60))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setCursor(QtCore.Qt.PointingHandCursor)

        self.label.setGeometry(0,0,60,60)
        pix = QtGui.QPixmap('resources\\click.png')
        self.label.setPixmap(pix)
        self.label.setScaledContents(True)

        self.label_2.setStyleSheet("font: 75 10pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.label_2.setGeometry(60, 0, 60, 30)
        self.label_2.setText(obj_name)

        self.add_Button.setIcon(QtGui.QIcon('resources/add.png'))
        self.sub_Button.setIcon(QtGui.QIcon('resources/sub.png'))

        self.label_3.setStyleSheet("font: 75 10pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.label_3.setText(str(self.click_number))

        self.add_Button.clicked.connect(self.add_click_event)
        self.sub_Button.clicked.connect(self.sub_click_event)
        x, y = position()
        self.setGeometry(x-25, y-4, 120, 60)

        self.useful_location = self.pos() + QtCore.QPoint(25, 4)

    def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self._isTracking = True
            self._startPos = a0.pos()
        # if a0.button() == QtCore.Qt.RightButton:
        #     menu = QtWidgets.QMenu(self)
        #     quit_action = menu.addAction("quit")
        #     action = menu.exec_(self.mapToGlobal(a0.pos()))
        #     if action == quit_action:
        #         QtWidgets.QApplication.quit()

    def mouseMoveEvent(self, a0: QtGui.QMouseEvent) -> None:
        if self._isTracking:
            self._endPos = a0.pos() - self._startPos
            self.move(self.pos() + self._endPos)

    def mouseReleaseEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self.useful_location = self.pos() + QtCore.QPoint(25, 4)
            self._isTracking = False
            self._startPos = None
            self._endPos = None
        if a0.button() == QtCore.Qt.RightButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None

    def add_click_event(self):
        self.click_number += 1
        self.label_3.setText(str(self.click_number))

    def sub_click_event(self):
        if self.click_number > 1:
            self.click_number -= 1
        self.label_3.setText(str(self.click_number))


class Input(QtWidgets.QDialog, UiInput):
    _startPos = None
    _endPos = None
    _isTracking = None
    useful_location = None
    action_name = 'input'
    test_info = None
    obj_name = None

    def __init__(self, obj_name):
        super().__init__()
        self.setupUi(self)
        self.obj_name = obj_name
        self.initUI(obj_name)

    def initUI(self, obj_name):
        self.setWindowTitle(obj_name)
        self.setObjectName(obj_name)  # 设置窗口名，相当于CSS中的ID
        self.setFixedSize(QtCore.QSize(270, 60))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setCursor(QtCore.Qt.PointingHandCursor)

        self.label.setGeometry(0, 0, 60, 60)
        pix = QtGui.QPixmap('resources\\input.png')
        self.label.setPixmap(pix)
        self.label.setScaledContents(True)

        self.label_2.setStyleSheet("font: 75 10pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.label_2.setGeometry(60, 0, 60, 30)
        self.label_2.setText(obj_name)

        self.comboBox.addItems(funtions)
        self.comboBox.setStyleSheet("font: 75 8pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit.setPlaceholderText("数据以英式';'隔开")
        self.lineEdit.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit_2.setPlaceholderText("请输入文件路径")
        self.lineEdit_2.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit_3.setPlaceholderText("请输入数据类型")
        self.lineEdit_3.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit_4.setPlaceholderText("请输入按键代码")
        self.lineEdit_4.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        # 控件显示初始化
        self.lineEdit_2.setVisible(False)
        self.lineEdit_3.setVisible(False)
        self.lineEdit_4.setVisible(False)

        # 事件绑定
        self.ok_Button.clicked.connect(self.ok_button_event)
        self.comboBox.activated.connect(self.currentIndexChangedEvent)

        x, y = position()
        self.setGeometry(x - 6, y - 51, 270, 60)

        # 有效定位初始化
        self.useful_location = self.pos() + QtCore.QPoint(6, 51)

    def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self._isTracking = True
            self._startPos = a0.pos()

    def mouseMoveEvent(self, a0: QtGui.QMouseEvent) -> None:
        if self._isTracking:
            self._endPos = a0.pos() - self._startPos
            self.move(self.pos() + self._endPos)

    def mouseReleaseEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self.useful_location = self.pos() + QtCore.QPoint(6, 51)
            self._isTracking = False
            self._startPos = None
            self._endPos = None
        if a0.button() == QtCore.Qt.RightButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None

    def control_show_choice(self,control):
        for con in [self.lineEdit, self.lineEdit_2, self.lineEdit_3, self.lineEdit_4]:
            con.setVisible(False)
        control.setVisible(True)
        self.ok_Button.setVisible(True)

    def text_choice(self, index):
        msg = None
        if index == 0:
            msg = self.lineEdit.text()
        elif index == 1:
            msg = self.lineEdit_2.text()
        elif index == 2:
            msg = self.lineEdit_3.text()
        elif index == 3:
            msg = self.lineEdit_4.text()
        return msg

    def currentIndexChangedEvent(self):
        if self.comboBox.currentIndex() == 0:
            self.control_show_choice(self.lineEdit)
        elif self.comboBox.currentIndex() == 1:
            self.control_show_choice(self.lineEdit_2)
        elif self.comboBox.currentIndex() == 2:
            self.control_show_choice(self.lineEdit_3)
        elif self.comboBox.currentIndex() == 3:
            self.control_show_choice(self.lineEdit_4)

    def ok_button_event(self):
        for control in [self.lineEdit, self.lineEdit_2, self.lineEdit_3, self.lineEdit_4, self.ok_Button]:
            control.setVisible(False)
        self.test_info = [self.comboBox.currentIndex(), self.text_choice(self.comboBox.currentIndex())]

        print(self.test_info)


class Wait(QtWidgets.QDialog, UiWait):
    action_name = 'wait'
    wait_time = '1'
    obj_name = None

    def __init__(self, obj_name):
        super().__init__()
        self.setupUi(self)
        self.obj_name = obj_name
        self.initUI(obj_name)

    def initUI(self, obj_name):
        self.setWindowTitle(obj_name)
        self.setObjectName(obj_name)  # 设置窗口名，相当于CSS中的ID
        self.setFixedSize(QtCore.QSize(120, 60))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setCursor(QtCore.Qt.PointingHandCursor)

        pix = QtGui.QPixmap('resources\\time.png')
        self.label.setPixmap(pix)
        self.label.setScaledContents(True)

        self.label_2.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.label_2.setGeometry(60, 0, 60, 30)
        self.label_2.setText(obj_name)

        self.lineEdit.setPlaceholderText("单位秒")
        self.lineEdit.setText('1')
        self.lineEdit.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit.textChanged.connect(self.text_changed_event)

    def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self._isTracking = True
            self._startPos = a0.pos()

    def mouseMoveEvent(self, a0: QtGui.QMouseEvent) -> None:
        if self._isTracking:
            self._endPos = a0.pos() - self._startPos
            self.move(self.pos() + self._endPos)

    def mouseReleaseEvent(self, a0: QtGui.QMouseEvent) -> None:
        if a0.button() == QtCore.Qt.LeftButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None
        if a0.button() == QtCore.Qt.RightButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None

    def text_changed_event(self):
        self.wait_time = self.lineEdit.text()


class Find(QtWidgets.QDialog, UiFind):
    action_name = 'find'
    location = None
    info = None
    obj_name = None

    def __init__(self, obj_name,folder_name):
        super().__init__()
        self.setupUi(self)
        self.obj_name = obj_name
        self.folder_name = folder_name
        self.initUI(obj_name)

    def initUI(self, obj_name):
        self.setWindowTitle(obj_name)
        self.setObjectName(obj_name)  # 设置窗口名，相当于CSS中的ID
        # self.setFixedSize(QtCore.QSize(120, 60))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool)
        # self.setWindowOpacity(0.3)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.setCursor(QtCore.Qt.PointingHandCursor)

        self.controls_hide()

        self.lineEdit.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.lineEdit_2.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")
        self.comboBox.setStyleSheet("font: 75 7pt \"Adobe Arabic\";color:rgb(255,0,0)")

        self.lineEdit.setPlaceholderText("对比文字")
        self.lineEdit_2.setText("0")
        self.comboBox.addItems(image_operation)

        self.ok_Button.clicked.connect(self.ok_button_event)
        self.comboBox.activated.connect(self.combobox_action_event)

        self.is_draw_flag = True

    def controls_hide(self):
        self.ok_Button.setVisible(False)
        self.lineEdit.setVisible(False)
        self.lineEdit_2.setVisible(False)
        self.comboBox.setVisible(False)
        self.label.setVisible(False)

    def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
        try:
            if self.is_draw_flag:
                if a0.button() == QtCore.Qt.LeftButton:
                    self.startPoint = a0.pos()
                    self.isLeftPress = True
                else:
                    self.isLeftPress = False
        except Exception as e:
            print(e)

    def mouseMoveEvent(self, a0: QtGui.QMouseEvent) -> None:
        try:
            if self.is_draw_flag:
                if hasattr(self, "isLeftPress") and self.isLeftPress:
                    self.endPoint = a0.pos()
                    self.repaint()
                    self.controls_hide()
        except Exception as e:
            print(e)

    def mouseReleaseEvent(self, a0: QtGui.QMouseEvent) -> None:
        try:
            if self.is_draw_flag:
                if a0.button() == QtCore.Qt.LeftButton:
                    self.endPoint = a0.pos()
                    self.isLeftPress = False
                    self.repaint()
                    self.adjust_region()
                    self.load_Image()
                    self.control_move()
                    self.combobox_action_event()
                if self.endPoint == self.startPoint:
                    self.controls_hide()

        except Exception as e:
            print(e)

    def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
        try:
            backPath = QtGui.QPainterPath()
            backPath.addRect(0, 0, self.width(), self.height())
            # fillPath = QtGui.QPainterPath()
            if hasattr(self, 'startPoint') and hasattr(self, "endPoint"):
                movePath = QtGui.QPainterPath()
                movePath.addRect(QtCore.QRectF(self.startPoint, self.endPoint))
                fillPath = backPath.subtracted(movePath)
            else:
                fillPath = backPath
            painter = QtGui.QPainter(self)
            # painter.drawImage(QtCore.QPoint(0, 0), self.backImg)
            painter.setPen(QtGui.QPen(QtGui.QColor(87, 170, 255), 5, QtCore.Qt.SolidLine))
            painter.drawPath(fillPath)
            painter.fillPath(fillPath, QtGui.QColor(0, 0, 0, 100))
        except Exception as e:
            print(e)

    def releaseMouse(self) -> None:
        pass

    def control_move(self):
        try:
            self.ok_Button.move(self.endPoint+QtCore.QPoint(-40, 0))
            self.lineEdit_2.move(self.endPoint+QtCore.QPoint(-70, 0))
            self.lineEdit.move(self.endPoint + QtCore.QPoint(-130, 0))
            self.comboBox.move(self.endPoint + QtCore.QPoint(-210, 0))
            # self.lineEdit.move(self.endPoint + QtCore.QPoint(-120, 0))
            self.ok_Button.setVisible(True)
            self.lineEdit_2.setVisible(True)
            self.lineEdit.setVisible(True)
            self.comboBox.setVisible(True)
            self.label.setVisible(True)
        except Exception as e:
            print(e)

    def adjust_region(self):
        x1 = self.startPoint.x()
        x2 = self.endPoint.x()
        if x2 < x1:
            self.endPoint.setX(x1)
            self.startPoint.setX(x2)
        y1 = self.startPoint.y()
        y2 = self.endPoint.y()
        if y2 < y1:
            self.endPoint.setY(y1)
            self.startPoint.setY(y2)

    def load_Image(self):
        clipboard = QtWidgets.QApplication.clipboard()
        pix = clipboard.pixmap()
        self.label.setGeometry(self.endPoint.x(), self.startPoint.y(), pix.width(), pix.height())
        self.label.setPixmap(pix)
        # self.label.pixmap().save('tmp/screen.png')

    def collect_info(self):
        self.location = [self.startPoint.x(),
                         self.startPoint.y(),
                         self.endPoint.x(),
                         self.endPoint.y()]
        if self.lineEdit.text() :
            choose = [1, self.lineEdit.text()]
        else:
            image_path = f'tmp/{self.folder_name}/contrast{str(int(time()))}.png'
            self.label.pixmap().save(image_path)
            choose = [0, image_path]
        self.info = [
            self.comboBox.currentIndex(),
            choose,
            int(self.lineEdit_2.text())
        ]

    def ok_button_event(self):
        self.collect_info()
        size = self.endPoint - self.startPoint
        self.setGeometry(self.startPoint.x()-10,
                         self.startPoint.y()-10,
                         size.x()+20,
                         size.y()+20)
        self.startPoint = QtCore.QPoint(10, 10)
        self.endPoint = QtCore.QPoint(size.x()+10, size.y()+10)
        self.repaint()
        self.controls_hide()

        self.is_draw_flag = False

    def combobox_action_event(self):
        if self.comboBox.currentIndex() == 0:
            self.lineEdit.setPlaceholderText("对比图片")
        elif self.comboBox.currentIndex() == 1:
            self.lineEdit.setPlaceholderText("对比文字")

